package com.imay.live.activity.recharge;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.WebViewActivity;
import com.imay.live.adapter.RechargeLinearAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.model.RechargeInfo;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.WxpayModel;
import com.imay.live.pay.PayResult;
import com.imay.live.pay.PayUtils;
import com.imay.live.proto.MessageId;
import com.imay.live.proto.ProtoResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.custom.AlipayRechargeView;
import com.imay.live.view.custom.LoadEmptyViewControl;
import com.imay.live.view.custom.PricePayViewModel;
import com.imay.live.view.custom.RechargeTitle;
import com.imay.live.view.custom.RechargeTitle2;
import com.imay.live.view.custom.WeixinRechargeView;
import com.imay.live.R;
import com.imay.live.wxapi.WXPayEntryActivity;
import com.imay.tbas_api.IMYTBASObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * create by nick
 * 我的-> 充值
 */
public class RechargeActivity extends BaseRequestActivity {
    public RecyclerView mrecyclerView;
    RechargeLinearAdapter mAdapter;
    ArrayList<MultiItemEntity> mdatas;
    WeixinRechargeView weixinRechargeView;
    AlipayRechargeView alipayRechargeView;
    PurchaseButton purchaseButton;
    PayUtils payUtils;
    PricePayViewModel pricePayViewModel;
    RechargeTitle2 rechargeTitle;
    LoadEmptyViewControl loadEmptyViewControl;
    View magreement;
    CheckBox sign_chekc;
    PurchaseDes button;

    public static void start(Context context) {
        Intent starter = new Intent(context, RechargeActivity.class);
        context.startActivity(starter);
    }

    final int gridnum = 3;
    final int griddivider = 30;
    private IWXAPI mapi;
    private int maxmoney = 3000;
    private IMYTBASObject mSocketNotify;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.mine_recharge));
        getTitleBar().addRightTextView(getResources().getString(R.string.recharge_history));
        getTitleBar().setRightTextOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyRechargeHistoryActivity.start(RechargeActivity.this, 0);
                MobclickAgent.onEvent(RechargeActivity.this,"diamond_click_paylists");
            }
        });
        mrecyclerView = $(R.id.rcv_charge);
        FrameLayout frame_layout = $(R.id.frame_layout);
        mdatas = new ArrayList<MultiItemEntity>();


        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, gridnum);
        mrecyclerView.setLayoutManager(gridLayoutManager);
        mAdapter = new RechargeLinearAdapter(mdatas);
        mAdapter.bindToRecyclerView(mrecyclerView);
        mrecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .size(griddivider).color(Color.WHITE)
                .build());

        mrecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ArrayList<MultiItemEntity> datas = (ArrayList<MultiItemEntity>) adapter.getData();
                if (datas == null || datas.isEmpty()) {
                    return;
                }
                pricePayViewModel = (PricePayViewModel) datas.get(position);
                if (pricePayViewModel.isChecked()) {
                    return;
                }
                for (MultiItemEntity multiItemEntity : datas) {
                    if (multiItemEntity instanceof PricePayViewModel) {
                        PricePayViewModel payViewModel = (PricePayViewModel) multiItemEntity;
                        if (payViewModel.isChecked()) {
                            payViewModel.setChecked(false);
                            break;
                        }

                    }
                }
                pricePayViewModel.setChecked(true);

                adapter.notifyDataSetChanged();
                if (weixinRechargeView.isChecked()) {
                    showTip();
                }
            }
        });

        loadEmptyViewControl = new LoadEmptyViewControl(RechargeActivity.this);
        loadEmptyViewControl.addLoadView(frame_layout);

        refreshLoad();
        registerSocketNotify();
        MobclickAgent.onEvent(this,"diamond_open");
    }

    //充值变化
    private void registerSocketNotify() {
        //监听socket
        mSocketNotify = new IMYTBASObject(false);
        mSocketNotify.stringCommand = EventHelper.EVENT_SOCK_NOTIFY;
        mSocketNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject object) {
                try {
                    if (object.socket_msg_id == MessageId.userMoneyUpdateNotify) {
                        JSONObject jsonObject = new JSONObject(object.socket_content);
                        final long diamond = jsonObject.getLong("diamond");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (rechargeTitle != null) {
                                    rechargeTitle.setText(diamond);

                                }

                            }
                        });
                        UserInfoModel userInfoModel = UserInfoCache.getUserInfo();
                        if (userInfoModel != null) {
                            UserInfoModel.MoneyModel moneyModel = userInfoModel.getMoney();
                            if (moneyModel != null) {
                                moneyModel.setDiamond(diamond);
                                UserInfoCache.saveUserInfo(userInfoModel);
                            }
                        }

                    } else if (object.socket_msg_id == MessageId.accountRechargeResultNotify) {
                        EventHelper.postRechargeSuccess();
                        refreshLoad();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        mSocketNotify.addEventListenWithTBASObject();
    }

    void showTip() {
        if (pricePayViewModel.getAndroidMoney() > maxmoney) {
            DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), "", getResources().getString(R.string.recharge_tis), getResources().getString(R.string.recharge_payzhifubao), getResources().getString(R.string.recharge_rechange), true, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    weixinRechargeView.setcheck(false);
                    alipayRechargeView.setcheck(true);
                    zhifubaoPay(RechargeActivity.this.pricePayViewModel.getId());
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pricePayViewModel = setTarget(maxmoney);
                    if (pricePayViewModel == null) {
                        pricePayViewModel = (PricePayViewModel) mdatas.get(0);
                    }

                }
            });
            return;
        }
    }

    private void loadSuccess(ArrayList<PricePayViewModel> data, final int totalRechargeDiamond) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        loadEmptyViewControl.loadcomplete();
        mrecyclerView.setVisibility(View.VISIBLE);
        mdatas.clear();
        mdatas.addAll(data);
        if (rechargeTitle == null) {
            rechargeTitle = new RechargeTitle2(RechargeActivity.this);
            UserInfoModel userInfoModel = UserInfoCache.getUserInfo();
            rechargeTitle.setText(0);
            if (userInfoModel != null) {
                UserInfoModel.MoneyModel moneyModel = userInfoModel.getMoney();
                if (moneyModel != null) {
                    rechargeTitle.setText(moneyModel.getDiamond());
                }
            }
            mAdapter.addHeaderView(rechargeTitle);
        }
        for (PricePayViewModel pricePayViewModel : data) {
            if (pricePayViewModel.getId().equals(PreferenceHelper.getInstance().getString(PreferenceHelper.CHARGE_ID))) {
                pricePayViewModel.setChecked(true);
                RechargeActivity.this.pricePayViewModel = pricePayViewModel;
//                                break;
            }
            if (totalRechargeDiamond > 0) {
                pricePayViewModel.setAndroidFirstReward(0);
            }
        }
        if (RechargeActivity.this.pricePayViewModel == null) {
            PricePayViewModel pricePayViewModel = data.get(0);
            pricePayViewModel.setChecked(true);
            RechargeActivity.this.pricePayViewModel = pricePayViewModel;
        }
        mAdapter.notifyDataSetChanged();
        if (weixinRechargeView == null) {
            weixinRechargeView = new WeixinRechargeView(RechargeActivity.this);
            alipayRechargeView = new AlipayRechargeView(RechargeActivity.this);
            mAdapter.addFooterView(weixinRechargeView);
            mAdapter.addFooterView(alipayRechargeView);
            RecharegButton recharegButton = new RecharegButton(RechargeActivity.this);
            mAdapter.addFooterView(recharegButton);
            purchaseButton = new PurchaseButton(RechargeActivity.this);
            mAdapter.addFooterView(purchaseButton);

//                            magreement = getagrementView(mrecyclerView);
//                            mAdapter.addFooterView(magreement);
        }
        int mode = PreferenceHelper.getInstance().getInt(PreferenceHelper.CHARGE_MODE, 1);
        if (mode == 0) {
            weixinRechargeView.setcheck(true);
            alipayRechargeView.setcheck(false);
        } else {
            alipayRechargeView.setcheck(true);
            weixinRechargeView.setcheck(false);
        }
        purchaseButton.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                if (button != null) {
                    mAdapter.removeFooterView(button);
                }
                purchaseButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                View view = LayoutInflater.from(RechargeActivity.this).inflate(R.layout.item_price, mrecyclerView, false);
                view.measure(view.getLayoutParams().width, view.getLayoutParams().height);
                int hig = mdatas.size() / gridnum;
                int higt = mdatas.size() % gridnum;
                if (higt != 0) {
                    hig++;
                }
                double y = purchaseButton.getBottom();
                int bottom = mrecyclerView.getMeasuredHeight();
                int bottomviewh = (int) (bottom - y - rechargeTitle.getBottom() - hig * view.getMeasuredHeight()) - griddivider * (hig + 1);
                if (bottomviewh < 80) {
                    bottomviewh = 80;
                }
                button = new PurchaseDes(RechargeActivity.this, bottomviewh);
                mAdapter.addFooterView(button);
            }
        });
    }

    private void getListInfo(final int totalRechargeDiamond) {
        ProtoRequestHelper.task(ProtoHttpFactory.getrechargeList()).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<ArrayList<PricePayViewModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<PricePayViewModel>>>() {
                    }.getType());
                    if (result.result == CodeSuccess && result.data != null) {
                        loadSuccess(result.data, totalRechargeDiamond);
                    } else {
                        loadEmptyViewControl.loadError();
                        mrecyclerView.setVisibility(View.GONE);
                    }

                } catch (Exception e) {
                    loadEmptyViewControl.loadError();
                    mrecyclerView.setVisibility(View.GONE);
                }

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadEmptyViewControl.loadError();
                mrecyclerView.setVisibility(View.GONE);

            }
        });
    }


    private void refreshLoad() {
        ProtoRequestHelper.task(ProtoHttpFactory.getrechargeInfo()).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<RechargeInfo> result = JSON.parseObject(data, new TypeReference<Result<RechargeInfo>>() {
                    }.getType());
                    if (result.result == CodeSuccess && result.data != null) {
                        getListInfo(result.data.getTotalRechargeDiamond());
                    } else {
                        loadEmptyViewControl.loadError();
                        mrecyclerView.setVisibility(View.GONE);
                    }

                } catch (Exception e) {
                    loadEmptyViewControl.loadError();
                    mrecyclerView.setVisibility(View.GONE);
                }

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                loadEmptyViewControl.loadError();
                mrecyclerView.setVisibility(View.GONE);
            }
        });

    }

    private View getagrementView(RecyclerView recyclerView) {
        View view = LayoutInflater.from(RechargeActivity.this).inflate(R.layout.view_agreement, recyclerView, false);
        sign_chekc = (CheckBox) view.findViewById(R.id.sign_chekc);
        TextView tv_signments = (TextView) view.findViewById(R.id.tv_signments);
        tv_signments.setTextColor(getResources().getColor(R.color.text_75));
        tv_signments.setGravity(Gravity.CENTER_HORIZONTAL);
        tv_signments.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sign_tipssize));
        String othertips = getResources().getString(R.string.recharge_agreement);
        SpannableString spanstring = new SpannableString(othertips);
        if (othertips.length() > 7) {
            spanstring.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    WebViewActivity.startActivity(RechargeActivity.this, UrlHelper.RECHARGE_LICENSE);
                }

                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(Color.parseColor("#507daf"));
                    ds.setUnderlineText(false);
                    ds.clearShadowLayer();
                }
            }, 7, othertips.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        tv_signments.setText(spanstring);
        tv_signments.setMovementMethod(LinkMovementMethod.getInstance());
        return view;
    }

    public void payCheck(View view, boolean check) {
        if (view instanceof WeixinRechargeView) {
            alipayRechargeView.setcheck(!check);
        } else {
            weixinRechargeView.setcheck(!check);
            if (weixinRechargeView.isChecked()) {
                showTip();
            }
        }

    }

    class RecharegButton extends LinearLayout {

        public RecharegButton(Context context) {
            super(context);
            inint(context);
        }

        public RecharegButton(Context context, AttributeSet attrs) {
            super(context, attrs);
            inint(context);
        }

        public RecharegButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            inint(context);
        }

        @RequiresApi(api = 21)
        public RecharegButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
            inint(context);
        }

        void inint(Context context) {
            setBackgroundColor(Color.WHITE);
            setOrientation(VERTICAL);
            TextView textView = new TextView(context);
            textView.setGravity(Gravity.CENTER);
            textView.setPadding(0, (int) getResources().getDimension(R.dimen.re_button_padding), 0, (int) getResources().getDimension(R.dimen.re_button_padding));
            textView.setTextColor(getResources().getColor(R.color.text_ff));
            textView.setText(getResources().getString(R.string.recharge_now));
            textView.setBackgroundResource(R.drawable.shape_corner100_9e);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            params.topMargin = (int) getResources().getDimension(R.dimen.re_button_top);
            params.bottomMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
            params.leftMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
            params.rightMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
            addView(textView, params);

            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (RechargeActivity.this.pricePayViewModel == null) {
                        return;
                    }
                    if (sign_chekc != null && !sign_chekc.isChecked()) {
                        ToastUtil.show(RechargeActivity.this, getResources().getString(R.string.recharge_readagreement));
                        return;
                    }
                    PreferenceHelper.getInstance().putString(PreferenceHelper.CHARGE_ID, RechargeActivity.this.pricePayViewModel.getId());

                    if (weixinRechargeView != null && weixinRechargeView.isChecked()) {
                        PreferenceHelper.getInstance().putInt(PreferenceHelper.CHARGE_MODE, 0);
                        weixinpay(RechargeActivity.this.pricePayViewModel.getId());
                    } else if (alipayRechargeView != null && alipayRechargeView.isChecked()) {
                        PreferenceHelper.getInstance().putInt(PreferenceHelper.CHARGE_MODE, 1);
                        zhifubaoPay(RechargeActivity.this.pricePayViewModel.getId());
                    }
                    MobclickAgent.onEvent(RechargeActivity.this,"diamond_click_pay");
                }
            });
        }
    }

    private PricePayViewModel setTarget(int target) {
        int len = mdatas.size();
        PricePayViewModel payViewModel = null;
        for (int i = len - 1; i > 0; i--) {
            MultiItemEntity multiItemEntity = mdatas.get(i);
            if (multiItemEntity instanceof PricePayViewModel) {
                PricePayViewModel pricePayViewModel = (PricePayViewModel) multiItemEntity;
                if (pricePayViewModel.getAndroidMoney() < target && payViewModel == null) {
                    pricePayViewModel.setChecked(true);
                    payViewModel = pricePayViewModel;
                } else {
                    pricePayViewModel.setChecked(false);
                }
            }
        }
        mAdapter.notifyDataSetChanged();
        return payViewModel;
    }

    private void zhifubaoPay(String id) {
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_loading));
        ProtoRequestHelper.task(ProtoHttpFactory.getalipay(id)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                Result<String> result = JSON.parseObject(data, new TypeReference<Result<String>>() {
                }.getType());
                if (result.result == CodeSuccess) {
                    if (result.data != null) {
                        if (payUtils == null) {
                            payUtils = new PayUtils(RechargeActivity.this);
                        }
                        try {
                            org.json.JSONObject jsonObject = new org.json.JSONObject(result.data);
                            payUtils.payV2(jsonObject.getString("data"), handler);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    ToastUtil.show(RechargeActivity.this, getResources().getString(R.string.put_fail));
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
//                    loadError(message);
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            }
        });
    }

    private void weixinpay(String id) {
        if (mapi == null) {
            mapi = WXAPIFactory.createWXAPI(RechargeActivity.this, WXPayEntryActivity.ID);
        }
        if (mapi.isWXAppInstalled()) {
            mapi.registerApp(WXPayEntryActivity.ID);
            boolean isPaySupported = mapi.getWXAppSupportAPI() >= com.tencent.mm.opensdk.constants.Build.PAY_SUPPORTED_SDK_INT;
            if (!isPaySupported) {
                ToastUtil.show(RechargeActivity.this, getResources().getString(R.string.recharge_installweixin));
                return;
            }
            DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_loading));
            ProtoRequestHelper.task(ProtoHttpFactory.getwxpayUrl(id)).setTag(this.hashCode()).request(new ProtoCallBack() {
                @Override
                public void onRequestSuccess(String command, String data) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    Result<WxpayModel> result = JSON.parseObject(data, new TypeReference<Result<WxpayModel>>() {
                    }.getType());
                    if (result.data != null) {
                        WxpayModel wxpayModel = result.data;
                        PayReq req = new PayReq();
                        req.appId = WXPayEntryActivity.ID;
                        req.partnerId = wxpayModel.getPartnerid();
                        req.prepayId = wxpayModel.getPrepayid();
                        req.nonceStr = wxpayModel.getNoncestr();
                        req.timeStamp = String.valueOf(wxpayModel.getTimestamp());
                        req.packageValue = wxpayModel.getPackageX();
                        req.sign = wxpayModel.getSign();
                        req.extData = "app data"; // optional
                        mapi.sendReq(req);
                    } else {
                        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    }

                }

                @Override
                public void onRequestError(String command, int code, String message) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                }
            });

        } else {
            ToastUtil.showImg(RechargeActivity.this, getString(R.string.recharge_uninstallweixin), R.mipmap.jiaohutishidaxia_3x, Toast.LENGTH_LONG);
        }
    }

    class PurchaseButton extends LinearLayout {

        public PurchaseButton(Context context) {
            super(context);
            inint(context);
        }

        public PurchaseButton(Context context, AttributeSet attrs) {
            super(context, attrs);
            inint(context);
        }

        public PurchaseButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            inint(context);
        }


        @RequiresApi(api = 21)
        public PurchaseButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
            inint(context);
        }

        void inint(Context context) {
            setOrientation(VERTICAL);
            setBackgroundColor(Color.WHITE);
            TextView textView = new TextView(context);
            textView.setGravity(Gravity.CENTER);
            textView.setPadding(0, (int) getResources().getDimension(R.dimen.re_button_padding), 0, (int) getResources().getDimension(R.dimen.re_button_padding));
            textView.setTextColor(getResources().getColor(R.color.color_9e));
            textView.setText(getResources().getString(R.string.recharge_pur));
            textView.setBackgroundResource(R.drawable.shape_sloid100_9e);
            LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER_HORIZONTAL;
//            params.topMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
            params.bottomMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
            params.leftMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
            params.rightMargin = (int) getResources().getDimension(R.dimen.re_button_margin);
            addView(textView, params);
            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(RechargeActivity.this,"diamond_click_meilipay");
                    BuyDiamondsActivity.start(RechargeActivity.this);
                }
            });

        }


    }

    class PurchaseDes extends LinearLayout {

        public PurchaseDes(Context context, int height) {
            super(context);
            inint(context, height);
        }

        void inint(Context context, int height) {
            setOrientation(VERTICAL);
            setBackgroundColor(Color.WHITE);
            TextView textView = new TextView(context);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.recharge_tips_size));
            textView.setTextColor(getResources().getColor(R.color.text_b2));
            textView.setText(getResources().getString(R.string.recharge_tips));
            textView.setPadding(0, 0, 0, 20);
            LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.height = height;
            textView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            addView(textView, params);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == PayUtils.SDK_PAY_FLAG) {
                @SuppressWarnings("unchecked")
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                /**
                 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtil.show(RechargeActivity.this, getResources().getString(R.string.pay_success));
//                    Toast.makeText(activity, "支付成功", Toast.LENGTH_SHORT).show();
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                    Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                    ToastUtil.show(RechargeActivity.this, getResources().getString(R.string.pay_fail));
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (mSocketNotify != null) {
            mSocketNotify.destroy();
        }
        super.onDestroy();

    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
